package com.core.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import com.core.dao.DAOException;
import com.core.dao.DAOFactory;
import com.core.entities.Contact;
import com.core.entities.Username;
import com.core.gui.helper.UserInfo;

public class UsernamSrv {
	
	private Username user;
	private Connection conn;

	public UsernamSrv(Connection conn) {

		this.conn = conn;
	}
	
	public List<String> getUsernamesNames(){
		List<String> usernamesNames = new ArrayList<String>();
		try{
			for(Username username : DAOFactory.getInstance().getUsernameDAO(conn).selectAll())
				usernamesNames.add(username.getUsername());
		}catch(DAOException e){
			e.printStackTrace();
		}
		return usernamesNames;
	}
	
	public List<String> getUsernamesByRole(String roleName){
		List<String> usernamesNames = new ArrayList<String>();
		try{
			for(Username username : DAOFactory.getInstance().getUsernameDAO(conn).getByRole(roleName))
				usernamesNames.add(username.getRole());
		}catch(DAOException e){
			e.printStackTrace();
		}
		return usernamesNames;
	}
	
	public int getUsernamePK(String username){
		try{
			return DAOFactory.getInstance().getUsernameDAO().getByUsername(username).get(0).getId();
		}catch(DAOException e){
			e.printStackTrace();
		}
		return user.getId();
	}
	
	public boolean login(String username, String password){
		List<Username> users;
		try{
			users = DAOFactory.getInstance().getUsernameDAO(conn).select("USERNAME =? AND PASSWORD = ?"
					, new Object[]{username, password});
			if(users.size() ==1){
				user = users.get(0);
				return true;
			}
		}catch(DAOException e){
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean isAdminCreatedBefor(){
		
		List<Username> users;
		try{
			users = DAOFactory.getInstance().getUsernameDAO(conn).select("ROLE=?", new Object[]{"admin"});
			if(users.size() > 0)
				return true;
		}catch(DAOException e){
			e.printStackTrace();
		}
		return false;
	}
	public boolean usernameIsExsist(String username){
		List<Username> users;
		try{
			users = DAOFactory.getInstance().getUsernameDAO(conn).select("USERNAME =?"
					, new Object[]{username});
		if(users.size() > 0)
				return true;
		}catch(DAOException e){
			e.printStackTrace();
		}
		return false;
	}
	
	private void validateRegistration(Contact contact , Username username) throws Exception {
		if(contact.getFirstName() == null || contact.getFirstName().equals("")) 
			throw new Exception("You must provide first name");
		if(contact.getLastName() == null || contact.getLastName().equals("")) 
			throw new Exception("You must provide last name");
		if(username.getUsername() == null || username.getPassword().equals("")) 
			throw new Exception("You must provid username");
		if(username.getPassword() == null || username.getPassword().equals("")) 
			throw new Exception("You must provid password");
		if(username.getPassword().equals(username.getPasswordConfirm()) == false) throw new
		Exception("Password does not match its confirmation");
	
	}
	
	public void register(Username username, Contact contact ) throws Exception{
		validateRegistration(contact, username);
		
		username.setUsername(username.getUsername());
		username.setPassword(username.getPassword());
		username.setPasswordConfirm(username.getPasswordConfirm());
		username.setRole(username.getRole());
//		if (UserInfo.getInstance().getService().getUsernamSrv()
//				.isAdminCreatedBefor()) {
//
//			username.setRole("user");
//		} else {
//			username.setRole("admin");
//		}
		
		
		DAOFactory.getInstance().getUsernameDAO().insert(username);

		
		contact.setFirstName(contact.getFirstName());
		contact.setSecondName(contact.getSecondName());
		contact.setLastName(contact.getLastName());
		contact.setMobileNumber(contact.getMobileNumber());
		contact.setEmail(contact.getEmail());
		int usernameId = UserInfo.getInstance().getService().getUsernamSrv()
				.getUsernamePK(username.getUsername());
		contact.setUsernameId(usernameId);
		
		DAOFactory.getInstance().getContactDAO().insert(contact);

	}
	
    public void changePassword(Username username, String oldPass, String newPass1, String newPass2) throws Exception{
        if(username.getPassword().equals(oldPass) == false)
            throw new Exception("Wrong old password");
        else if(newPass1.equals(newPass2) == false)
            throw new Exception("Password confirmation does not match");
        else if(oldPass.equals(newPass1))
            throw new Exception("New password is the same as the old one");
        else{
            username.setPassword(newPass1);
            DAOFactory.getInstance().getUsernameDAO().update(username);
        }
    }
	
//	
//    private String digest(String input){
//        MessageDigest md;
//        try {
//            md = MessageDigest.getInstance("MD5");
//            md.update(input.getBytes());
//            return new BASE64Encoder().encode(md.digest());
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

	public Username getUser() {
		return user;
	}

	public void setUser(Username user) {
		this.user = user;
	}
    
}
